package ua.kiev.tosik.price.modules.clients.database.files;

import org.apache.log4j.Logger;
import ua.kiev.tosik.price.conf.AppConfig;
import ua.kiev.tosik.price.database.dao.IPricesFilesDao;
import ua.kiev.tosik.price.database.factory.AbstractDbFactory;
import ua.kiev.tosik.price.models.PricesFiles;

import javax.swing.*;

public class PricesFilesDeleteWorker extends SwingWorker<Boolean, Void> {

	private static Logger logger = Logger.getLogger("ua.kiev.tosik.price.modules.clients.database.files");
	private PricesFiles pricesFiles;
	private IPricesFilesDao pricesFilesDao;
	private int rowIndex;

	public PricesFilesDeleteWorker() {
		super();
		logger.debug("Initialize PricesFilesDeleteWorker");
		try {
			pricesFilesDao = AbstractDbFactory.getInstance(AppConfig.getInstance().get("app.dbtype")).createPricesFilesDao();
		} catch (Exception e) {
			logger.error(e);
		}
	}

	public void setPricesFiles(PricesFiles pricesFiles) {
		this.pricesFiles = pricesFiles;
	}

	@Override
	protected Boolean doInBackground() throws Exception {
		boolean result = false;
		if ( pricesFiles == null ) {
			throw new Exception("Can't delete prices file. PricesFiles = NULL!");
		}
		firePropertyChange("FILE_DELETE_START", null, true);
		try {
			pricesFilesDao.delete(pricesFiles);
			result = true;
		} catch (Exception e) {
			logger.error(e);
			throw new Exception(e);
		}
		firePropertyChange("FILE_DELETE_DONE", null, true);
		return result;
	}

	@Override
	protected void done() {
		super.done();
		try {
			boolean result = get();
			firePropertyChange("FILE_DELETE_OK", null, rowIndex);
		} catch (Exception e) {
			logger.error(e);
			firePropertyChange("FILE_DELETE_ERROR", null, e);
		}
	}

	public void setRowIndex(int rowIndex) {
		this.rowIndex = rowIndex;
	}
}
